package cn.hyatt.common.utils;

import cn.hyatt.common.exception.BusinessException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;

/**
 * JWT工具
 *
 * @author hyatt
 */
@Slf4j
public class JwtUtil {

    public static String createJWT(String key, Long exp, Map<String, Object> claims) {

        try {
            // 密钥
            SecretKey secretKey = Keys.hmacShaKeyFor(key.getBytes(StandardCharsets.UTF_8));
            // 时间
            long currentTime = System.currentTimeMillis();
            Date currentTimeDate = new Date(currentTime);
            Date expirationTimeDate = new Date(currentTime + exp);

            return Jwts.builder()
                    // 发布时间
                    .issuedAt(currentTimeDate)
                    // 信息
                    .claims(claims)
                    // 设置签名
                    .signWith(secretKey)
                    // 设置指定时间之前无效
                    .notBefore(currentTimeDate)
                    // 设置过期时间
                    .expiration(expirationTimeDate)
                    .compact();
        }catch (Exception e) {
            throw new BusinessException("");
        }
    }

    public static Claims parseJWT(String key, String token) {
        // 密钥
        SecretKey secretKey = Keys.hmacShaKeyFor(key.getBytes(StandardCharsets.UTF_8));
        JwtParser build = Jwts.parser()
                .verifyWith(secretKey)
                .build();
        return build
                .parseSignedClaims(token)
                .getPayload();
    }
}
